package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.vo.GoodsOrderSendVo;
import com.ruoyi.system.domain.GoodsChoice;
import com.ruoyi.system.domain.GoodsLogistics;
import com.ruoyi.system.domain.GoodsOrder;
import com.ruoyi.system.domain.WxUser;
import com.ruoyi.system.domain.vo.GoodsOrderUpdateVo;
import com.ruoyi.system.domain.vo.GoodsOrderVo;
import com.ruoyi.system.mapper.GoodsChoiceMapper;
import com.ruoyi.system.mapper.GoodsOrderMapper;
import com.ruoyi.system.service.GoodsChoiceService;
import com.ruoyi.system.service.GoodsLogisticsService;
import com.ruoyi.system.service.GoodsOrderService;
import com.ruoyi.system.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

/**
 * (GoodsOrder)表服务实现类
 *
 * @author makejava
 * @since 2020-10-26 18:19:21
 */
@Service("goodsOrderService")
public class GoodsOrderServiceImpl implements GoodsOrderService {
    @Resource
    private GoodsOrderMapper goodsOrderDao;
    @Resource
    private GoodsChoiceService goodsChoiceService;
    @Resource
    private GoodsLogisticsService goodsLogisticsService;
    @Resource
    private GoodsChoiceMapper goodsChoiceMapper;
    @Autowired
    private WxUserService wxUserService;
    // @Autowired
    // private WxMessageService wxMessageService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    @Cacheable(value = "goods:order:info", key = "#p0")
    public GoodsOrder queryById(Integer id) {
        return this.goodsOrderDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @return 对象列表
     */
    @Override
    public List<GoodsOrder> queryAllByLimit(LoginUser loginUser, String status) {
        SysUser user = loginUser.getUser();
        return this.goodsOrderDao.queryAllByLimit(user.getUserId(), status);
    }

    /**
     * 管理员查询分页列表数据
     *
     * @param status 状态
     * @return 对象列表
     */
    @Override
    public List<GoodsOrderVo> adminQueryAllByLimit(String status, String phone, String title) {
        if (title != null && !"".equalsIgnoreCase(title)) title = "%" + title + "%";
        return this.goodsOrderDao.adminQueryAllByLimit(status, phone, title);
    }

    /**
     * 新增数据
     *
     * @param goodsOrder 实例对象
     * @return 实例对象
     */
    @Override
    public GoodsOrder insert(GoodsOrder goodsOrder, LoginUser loginUser) {
        goodsOrder.setAccountName(JSON.toJSONString(goodsOrder.getAccountNameList()));
        SysUser user = loginUser.getUser();
        GoodsChoice goodsChoice = goodsChoiceService.queryById(Integer.parseInt(goodsOrder.getGoodsId()));
        goodsOrder
                .setUserId(user.getUserId().toString())
//                .setUserName(user.getUserName())
                .setStatus("0")
                .setOrderNum(orderNum(user.getUserId().toString()))
                .setTitle(goodsChoice.getName())
                .setPrice(goodsChoice.getPrice())
                .setStart(goodsChoice.getStart())
                .setEnd(goodsChoice.getEnd())
                .setImg(goodsChoice.getImage())
                .setMerchantId(goodsChoice.getUserId())
                .setSalary(goodsChoice.getCommission());
        // WxUser wxUser = wxUserService.queryById(Integer.parseInt(goodsOrder.getUserId()));
        // wxMessageService.sendCommonMessage(WxMessageUtils.getCommonMsgVo(wxUser.getOpenId(), "你申请的样品" + "【" + goodsOrder.getTitle() + "】有达人申请"));
        this.goodsOrderDao.insert(goodsOrder);
        return goodsOrder;
    }

    /**
     * 修改数据
     *
     * @param goodsOrderUpdateVo 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    @CacheEvict(value = "goods:order:info", key = "#p0.goodsOrder.id")
    public GoodsOrder update(GoodsOrderUpdateVo goodsOrderUpdateVo) {
        GoodsOrder goodsOrder = goodsOrderUpdateVo.getGoodsOrder();
        if ("1".equalsIgnoreCase(goodsOrder.getStatus())) {
//            GoodsChoice goodsChoice1 = goodsChoiceService.queryById(Integer.parseInt(goodsOrder.getGoodsId()));
//            if (goodsChoice1 == null) return null;
//            GoodsChoice goodsChoice = new GoodsChoice();
//            goodsChoice.setId(Integer.parseInt(goodsOrder.getGoodsId()));
//            goodsChoice.setSales((Integer.parseInt(goodsChoice1.getSales() == null ? "0" : goodsChoice1.getSales()) + 1) + "");
//            if (goodsChoice1.getRemainNum() == null || "0".equalsIgnoreCase(goodsChoice1.getRemainNum())) return null;
//            goodsChoice.setRemainNum((Integer.parseInt(goodsChoice1.getRemainNum()) - 1) + "");
//            goodsChoiceService.update(goodsChoice);
        }
        if ("2".equalsIgnoreCase(goodsOrder.getStatus())) {
            GoodsLogistics goodsLogistics = goodsOrderUpdateVo.getGoodsLogistics();
            goodsLogistics.setOrderId(goodsOrder.getOrderNum());
            goodsLogisticsService.insert(goodsLogistics);
        }
        this.goodsOrderDao.update(goodsOrder);
        return this.queryById(goodsOrder.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.goodsOrderDao.deleteById(id) > 0;
    }

    /**
     * 发货
     *
     * @param goodsOrderSendVo 发货信息
     */
    @Override
    @Transactional
    @CacheEvict(value = "goods:order:info", key = "#p0.order")
    public void orderSendGoods(GoodsOrderSendVo goodsOrderSendVo) {
        GoodsOrder goodsOrder = new GoodsOrder();
        goodsOrder.setId(Integer.parseInt(goodsOrderSendVo.getOrder()))
                .setStatus("2")
                .setLogisticsId(goodsOrderSendVo.getLogisticsNum());
        goodsOrderDao.update(goodsOrder);
        GoodsLogistics goodsLogistics = new GoodsLogistics();
        goodsLogistics
                .setOrderId(goodsOrderSendVo.getOrderId())
                .setLogisticsNum(goodsOrderSendVo.getLogisticsNum())
                .setLogisticsName(goodsOrderSendVo.getLogisticsName());
        goodsLogisticsService.insert(goodsLogistics);
    }

    /***
     * 通过商家id获取订单信息
     * @param merchantId
     * @return
     */
    @Override
    public List<GoodsOrder> getOrderInfoByUserId(String merchantId, GoodsOrder reqGoodsOrder) {
        String phone = reqGoodsOrder.getPhone();
        String status = reqGoodsOrder.getStatus();
        String title = reqGoodsOrder.getTitle();
        if (title != null && !"".equalsIgnoreCase(title)) title = "%" + title + "%";
        List<GoodsOrder> goodsList = goodsOrderDao.goodsListByGoodsId(merchantId, phone, status, title);
        return goodsList;
    }

    @Override
    public void commitWork(String orderId, String content) {
        GoodsOrder goodsOrder = new GoodsOrder();
        goodsOrder.setId(Integer.parseInt(orderId)).setWorkContent(content).setStatus("6");
        goodsOrderDao.update(goodsOrder);
    }

    /**
     * 生成订单号
     *
     * @param userId 用户Id
     * @return 订单号
     */
    private String orderNum(String userId) {
        DateTimeFormatter yyyyMMddHHmmss = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        StringBuilder format = new StringBuilder(yyyyMMddHHmmss.format(LocalDateTime.now()));
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            format.append(random.nextInt(9));
        }
        return format.append(userId).toString();
    }
}
